{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d1f20875-c50d-46df-906b-49ec1d0c6002",
   "metadata": {},
   "source": [
    "# 6.7 实现Softmax函数"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c90a18b9-d8e8-431c-856c-35f1e4ed05e1",
   "metadata": {},
   "source": [
    "### 1.任务描述\n",
    "\n",
    "假设有3个类别。对于某个样本，通过线性计算得到样本对于3个类别的线性输出分别为2,5,9。\n",
    "\n",
    "要求：\n",
    "\n",
    "- 通过Softmax函数，将3个线性输出转换为样本分别属于3个类别的概率值。\n",
    "- 求3个概率值的和"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "f5b4fc39-cbcf-432a-bf1e-e75e642d4b87",
   "metadata": {},
   "source": [
    "### 2.知识准备\n",
    "\n",
    "见教程。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b624ebee-980f-4c1e-b963-a24ff0b669f6",
   "metadata": {},
   "source": [
    "### 3.任务分析\n",
    "\n",
    "在tensorflow.nn的库中实现原生Softmax激活函数。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "435c6090-cfda-4f46-a550-22a368e41e4a",
   "metadata": {},
   "source": [
    "### 4.任务实施\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ec75eb6c-5da3-467d-a471-ca3b47242dd6",
   "metadata": {},
   "source": [
    "执行代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2ae9da58-e339-4d22-9f8d-ca255711d89e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "样本属于三个类别的概率值分别为： [8.9467951e-04 1.7970119e-02 9.8113519e-01]\n",
      "三个概率值的和为： 1.0\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "# 样本属于三个类别的线性输出分别为2,5,9\n",
    "lineout=tf.constant([2,5,9],dtype=tf.float32)\n",
    "# 将线性输出转换为概率值\n",
    "PRED = tf.nn.softmax(lineout)\n",
    "print(\"样本属于三个类别的概率值分别为：\",PRED.numpy())\n",
    "# 求三个概率值的和\n",
    "result=tf.reduce_sum(PRED)\n",
    "print(\"三个概率值的和为：\",result.numpy())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
